// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  traceUser: true,
  env: 'aaa111-9gh9fp5ieac4de5d'
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContent = cloud.getWXContext()
  var result=[]
  try {
    var temp1 = await db.collection('postinfo').orderBy('timestamp',"desc").get()
  } catch (e) {
    console.error(e)
  }
  console.log(temp1.data)
  if (temp1.data.length > 0) {
    for (var i = 0; i < temp1.data.length; i++) {
      var tempObject = {}
      try {
        var temp2 = await db.collection('user').where({
          _openid: temp1.data[i]._openid
        }).get()
        tempObject.userInfo = temp2.data[0]
        tempObject.postInfo = temp1.data[i]
      } catch(e){
        console.error(e)
      }

      try {
        var viewnum = await db.collection('postReadHistory').where({
          artId: temp1.data[i]._id
        }).count()
        tempObject.viewNum = viewnum.total
      } catch(e){
        console.error(e)
      }

      result.push(tempObject)
    };
  }
  //console.log(result)
  return result
}